"""测试过程中的全局对象"""
# -*- coding:utf-8 -*-

import os
import time
import datetime
import uuid
import logging
from ppts.core.ReportGenerate import parse_result_data, generate_json_file, generate_excel_file, generate_html_file \
    , generate_csv_file
from ppts.core.SeleniumUtil import init_web_driver, collect_pts_data, test_url
from ppts.core.TestUtil import parse_config, execute_script, create_current_result_folder
from ppts.entity.PagePerformanceData import PagePerformanceData


class GlobalTestObject:
    driver = None
    test_config = None
    result_path = None
    screenshot_path = None

    def __init__(self):
        pass

    def start(self, config_name):
        logging.info('解析配置文件...')
        self.test_config = parse_config(config_name)
        if len(self.test_config.test_urls) == 0:
            raise Exception('要测试的URL不能为空')

        self.result_path = create_current_result_folder()
        self.screenshot_path = os.path.join(self.result_path, 'screenshot')

        if self.test_config.start_script is not None:
            logging.info('执行前置处理脚本...')
            execute_script(self.test_config.start_script)

        # 需要根据self.test_config.repeat来确定需要循环多少次
        i = 0
        logging.info('开始执行测试:')
        self.test_config.start_time = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        t1 = time.time()
        while i < self.test_config.repeat:
            i = i + 1
            logging.info(f'执行第{str(i)}次...')
            # 重启webDriver已达到清除缓存的目的
            if not self.test_config.cache and self.driver is not None:
                self.driver.quit()
                self.driver = None
            if self.driver is None:
                self.init_driver()
            for url in self.test_config.test_urls:
                pts_data = PagePerformanceData()
                # noinspection PyBroadException
                try:
                    start_time = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
                    b = time.time()
                    custom_pts_data = test_url(self.driver, url)
                    if self.test_config.test_interval_time > 0:
                        time.sleep(self.test_config.test_interval_time)
                    if custom_pts_data is not None:
                        pts_data = custom_pts_data
                    e = time.time()
                    if url.name is None or len(url.name) == 0:
                        url.name = self.driver.title
                    if url.url is None or len(url.url) == 0:
                        url.url = self.driver.current_url
                    # 如果设置了collect_data为False则不会收集数据
                    if url.collect_data and custom_pts_data is None:
                        pts_data = collect_pts_data(self.driver)
                    pts_data.start_time = start_time
                    pts_data.use_time = int(round((e - b) * 1000))
                    # 是否需要截图
                    if url.screenshot:
                        pts_data.screenshot_path = os.path.join(self.screenshot_path, ''.join(str(uuid.uuid1())
                                                                                              .split('-')) + '.png')
                        self.driver.get_screenshot_as_file(pts_data.screenshot_path)
                except Exception as e:
                    logging.error(f'运行测试URL出错:{str(e)}')
                    # 出错则设置为错误，并自动截图
                    pts_data.success = False
                    pts_data.error_msg = str(e)
                    # 自动截图
                    pts_data.screenshot_path = os.path.join(self.screenshot_path, ''.join(str(uuid.uuid1())
                                                                                          .split('-')) + '.png')
                    self.driver.get_screenshot_as_file(pts_data.screenshot_path)
                finally:
                    url.pts_data.append(pts_data)
        t2 = time.time()
        self.test_config.complete_time = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        self.test_config.use_time = int(round((t2 - t1) * 1000))
        logging.info(f'测试已完成，共执行测试{str(i)}次!')
        # 退出webDriver
        if self.driver is not None:
            self.driver.quit()
        # 计算性能数据
        for url in self.test_config.test_urls:
            if url.collect_data:
                url.count_data()
        # 生成报告文件
        json = parse_result_data(self.test_config)
        # logging.info(f'测试结果详细json数据:{str(json)}')
        report_path = os.path.join(self.result_path, self.test_config.report_name)
        if self.test_config.report_type == 'html':
            report_path = generate_html_file(json, report_path)
        elif self.test_config.report_type == 'csv':
            report_path = generate_csv_file(json, report_path)
        elif self.test_config.report_type == 'excel':
            report_path = generate_excel_file(json, report_path)
        elif self.test_config.report_type == 'json':
            report_path = generate_json_file(json, report_path)
        else:
            raise Exception(f'不支持的报告类型{self.test_config.report_type}')
        logging.info(f'生成测试报告成功，报告路径为:{report_path}')
        # 执行后置脚本
        if self.test_config.complete_script is not None:
            logging.info('执行后置处理脚本...')
            execute_script(self.test_config.complete_script)
        logging.info(f'测试完成，结果文件请查看文件夹 {self.result_path}')

    # 初始化webDriver
    def init_driver(self):
        self.driver = init_web_driver(browser_type=self.test_config.browser_type
                                      , driver_path=self.test_config.driver_path
                                      , no_headless=self.test_config.no_headless
                                      , cache=self.test_config.cache
                                      , timeout=self.test_config.page_load_timeout
                                      , user_agent=self.test_config.user_agent
                                      , cookie_list=self.test_config.cookie_list
                                      , browser_path=self.test_config.browser_path)


global_test_object = GlobalTestObject()
